package com.wenkang.stu.controller;

import com.wenkang.stu.enums.ExceptionEnums;
import com.wenkang.stu.exception.KangException;
import com.wenkang.stu.pojo.SysUser;
import com.wenkang.stu.service.SysUserService;
import com.wenkang.stu.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private SysUserService userService;

    @GetMapping
    public ResponseEntity<SysUser> getCurrentUser() {
        SysUser user = userService.selectByUsername((String) SecurityContextHolder.getContext().getAuthentication().getPrincipal());
        if (user != null) {
            return ResponseEntity.ok(user);
        }
        throw new KangException(ExceptionEnums.USER_NOT_FIND);
    }


    @GetMapping("page")
    public ResponseEntity<PageResult> getUserByPage(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "search", required = false) String search,
            @RequestParam(value = "desc", required = false) Boolean[] desc,
            @RequestParam(value = "sortBy", required = false) String[] sortBy
    ) {
        PageResult<SysUser> pageResult = userService.selectByPage(page, pageSize, search, desc, sortBy);
        return ResponseEntity.ok(pageResult);
    }

    @GetMapping("{userId}")
    public ResponseEntity<SysUser> getUserById(@PathVariable("userId") Integer userId) {
        SysUser user = userService.getById(userId);
        if (user != null) {
            return ResponseEntity.ok(user);
        }
        throw new KangException(ExceptionEnums.USER_NOT_FIND);
    }

    @PostMapping
    public ResponseEntity<Void> addUser(@RequestBody SysUser user) {
        if (user.getPassword() == null) {

        }
        if (userService.save(user)) {
            return ResponseEntity.status(HttpStatus.CREATED).build();
        }
        throw new KangException(ExceptionEnums.CREATED_ERROR);
    }

    @PutMapping
    public ResponseEntity<Void> updateUser(@RequestBody SysUser user) {
        userService.updateUser(user);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    @DeleteMapping("{userId}")
    public ResponseEntity<Void> deleteUser(@PathVariable("userId") Integer userId) {
        if (userService.removeById(userId)) {
            return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
        }
        throw new KangException(ExceptionEnums.DELETE_ERROR);
    }
}
